package com.family.gmall.payment.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.family.gmall.common.result.Result;
import com.family.gmall.model.enums.PaymentType;
import com.family.gmall.model.order.PaymentInfo;
import com.family.gmall.payment.config.AlipayConfig;
import com.family.gmall.payment.service.AlipayService;
import com.family.gmall.payment.service.PaymentService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.Map;

/**
 * @Auther: family
 * @Date: 2023/8/6 20:49
 * @Description:
 */
@Controller
@RequestMapping("/api/payment/alipay")
public class AlipayController {
    @Resource
    private AlipayService alipayService;

    @Resource
    private PaymentService paymentService;

    @RequestMapping("/submit/{orderId}")
    @ResponseBody
    public String submitOrder(@PathVariable Long orderId) {
        return alipayService.createAliPay(orderId);
    }

    /**
     * 支付宝回调
     *
     * @return
     */
    @RequestMapping("callback/return")
    public String callBack() {
        // 同步回调给用户展示信息
        return "redirect:" + AlipayConfig.return_order_url;
    }

    @PostMapping("/callback/notify")
    public String callbackNotify(@RequestParam Map<String, String> paramMap) {
        System.out.println("你回来了....");
        boolean signVerified = false;
        try {
            //验签
            signVerified = AlipaySignature.rsaCheckV1(
                    paramMap,
                    AlipayConfig.alipay_public_key,
                    AlipayConfig.charset,
                    AlipayConfig.sign_type);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        String tradeStatus = paramMap.get("trade_status");
        String outTradeNo = paramMap.get("out_trade_no");
        PaymentInfo paymentInfo = paymentService.getPaymentInfo(outTradeNo, PaymentType.ALIPAY.name());
        if (paymentInfo == null) {
            return "failure";
        }

        if (signVerified) {
            //TODO 验签成功
            if ("TRADE_SUCCESS".equals(tradeStatus) || "TRADE_FINISHED".equals(tradeStatus)) {
                paymentService.paySuccess(outTradeNo, PaymentType.ALIPAY.name(), paramMap);
                return "success";
            }
            return "failure";
        } else {
            //TODO 验签失败记录日志
            return "failure";
        }
    }

    @RequestMapping("refund/{orderId}")
    @ResponseBody
    public Result refund(@PathVariable(value = "orderId") Long orderId) {
        // 调用退款接口
        boolean flag = alipayService.refund(orderId);
        return Result.ok(flag);
    }
}
